<?php
/**
 *+------------------
 * madong
 *+------------------
 * Copyright (c) https://gitee.com/motion-code  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Official Website: http://www.madong.tech
 */

namespace madong\laravel\wf\dao;

use madong\ingenious\enums\ProcessTaskStateEnum;
use madong\ingenious\interface\model\IProcessTask;
use madong\laravel\wf\basic\BaseDao;
use madong\laravel\wf\model\ProcessTask;
use madong\ingenious\libs\utils\ArrayHelper;

class ProcessTaskDao extends BaseDao
{

    protected function setModel(): string
    {
        return ProcessTask::class;
    }

    /**
     * 任务详情
     *
     * @param $where
     * @param $field
     *
     * @return \madong\ingenious\interface\model\IProcessTask|null
     */
    public function getDetail($where = [], $field = ['*']): ?IProcessTask
    {
        $tmap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['id'],
            ['task_name', '', '', 'name'],
            ['task_state',ProcessTaskStateEnum::DOING->value],
            ['perform_type'],
            ['task_display_name', '', '', 'display_name'],
            ['operator'],
        ]));
        $imap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['business_no'],
            ['instance_name', '', '', 'name'],
            ['instance_display_name', '', '', 'display_name'],
        ]));

        $dmap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['process_name', '', '', 'name'],
            ['process_display_name', '', '', 'display_name'],
        ]));
        $query = $this->getModel()->with(['instance.define','actors'])
            ->where($tmap)
            ->whereHas('instance', function ($query) use ($imap, $dmap) {
                if (!empty($imap)) {
                    $query->where($imap);
                }
                // 将 $dmap 的条件放入 define 的子闭包中
                $query->whereHas('define', function ($query) use ($dmap) {
                    if (!empty($dmap)) {
                        $query->where($dmap);
                    }
                });
            })
            ->orderBy('create_time', 'desc')
            ->first();
        return $query ?? null;
    }
}
